package com.bbcare.treat.plat.controller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.treat.plat.service.IPtTaskTreatService;

/**
 * @name: 患者门诊诊疗相关处理类
 * @author: wuyz
 * @createTime: 2017.8.16
 * @description: 患者门诊诊疗相关操作
 * @modify:
 *
 */
@Controller
@RequestMapping("/service/treat")
public class PtTaskTreatController {
    private final Log logger = LogFactory.getLog(PtTaskTreatController.class);

    @Autowired
    private IPtTaskTreatService ptTaskTreatService;

    @Autowired
    private IPatientService patientSerivce;

    // 查询队列下关联的多个方案，建档时供医生选择
    @ResponseBody
    @RequestMapping("/listQueueScheme")
    public ResultModel<Map<String, Object>> listQueueScheme(@RequestBody String arg) throws Exception {
        logger.warn("in listscheme----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        String queueId = jsonData.getString("followQueueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，队列id为空！"));
        }
        Map<String, Object> mapIn = new HashMap<String, Object>();
        mapIn.put("queueId", queueId);
        Map<String, Object> mapOut = ptTaskTreatService.listscheme(mapIn);

        return new ResultModel<Map<String, Object>>(mapOut);
    }

    // 查询方案内容
    @ResponseBody
    @RequestMapping("/qryTaskContent")
    public ResultModel<Map<String, Object>> qryTaskContent(@RequestBody String arg) throws Exception {
        logger.warn("in getQueueArchiveContent----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        String taskId = jsonData.getString("taskId");
        if (StringUtils.isBlank(taskId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，任务id为空！"));
        }

        String schemeBusiType = jsonData.getString("schemeBusiType");
        if (StringUtils.isBlank(schemeBusiType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，任务id为空！"));
        }

        retMap = ptTaskTreatService.qryTaskContent(jsonData);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 任务提交函数
    @ResponseBody
    @RequestMapping("/submitTaskFunciton")
    public ResultModel<Map<String, Object>> submitTaskFunciton(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in submitTaskFunciton----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        JSONObject jsonTask = jsonData.getJSONObject("task");
        if (null == jsonTask) {
            // 前台必须传task节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无task节点！"));
        }
        JSONObject jsonOpInfo = jsonData.getJSONObject("oprInfo");
        if (null == jsonOpInfo) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无oprInfo节点！"));
        }
        // 方案业务类型
        String schemeBusiType = jsonOpInfo.getString("schemeBusiType");
        if (StringUtils.isBlank(schemeBusiType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入方案类型或值为空！"));
        }
        int schemeBusiTypes = Integer.parseInt(schemeBusiType);

        String opCode = jsonOpInfo.getString("opCode");
        if (StringUtils.isBlank(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无操作编码节点！"));
        }
        String queueId = jsonOpInfo.getString("followQueueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无队列id节点！"));
        }
        String ptSchemeId = jsonOpInfo.getString("ptSchemeId");
        if (StringUtils.isBlank(ptSchemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者队列实例id或值为空！"));
        }
        String userId = jsonOpInfo.getString("patientId");
        if (null == userId || "".equals(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，患者id未传或值为空！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String author = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = "";
        String deptId = (String) sessionMap.get("deptId");// 租户id
        paramMap.put("authorName", authorName);
        // 修改手机号同步app 使用
        paramMap.put("deptId", deptId);

        String taskId = jsonTask.getString("ptTaskId");
        String task = jsonTask.getString("taskId");
        if (StringUtils.isBlank(task) && StringUtils.isBlank(task)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入患者任务id或值为空！"));
        }
        String seqNo = jsonTask.getString("seqNo");
        boolean initTask = false;// 建档任务
        if (!StringUtils.isEmpty(seqNo)) {
            if (seqNo.equals("" + Constants.TASK_SEQ_FOR_INIT)) {
                initTask = true;
            }
        }

        String finishDate = jsonTask.getString("finishDate");
        if (schemeBusiTypes == Constants.SCHEME_BUSI_TYPE_0) {
            if (!initTask && StringUtils.isBlank(finishDate)) {
                // 建档可以不传随访日期
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "未传入随访日期或值为空！"));
            }
        }
        String updateAuname = jsonTask.getString("updateAuname");
        if (StringUtils.isBlank(updateAuname)) {
            updateAuname = authorName;
        }

        JSONArray ptContentIds = jsonTask.getJSONArray("ptContentIds");
        if (schemeBusiTypes == Constants.SCHEME_BUSI_TYPE_0) {
            if (null == ptContentIds || 0 == ptContentIds.size()) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                        "入参节点错误，未传入患者任务内容id节点或值为空！"));
            }
        }
        Map<String, Object> quesMap = jsonData.getJSONObject("questiones");
        if (MapUtils.isEmpty(quesMap)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    "入参节点错误，未传入任务内容报文或值为空！"));
        }
        // 生物样本采集信息（安医大需求）
        JSONArray sampleList = jsonData.getJSONArray("sampleList");
        if (null != sampleList) {
            paramMap.put("sampleList", sampleList);
        }

        String currTime = jsonOpInfo.getString("opTime");// 入参中有操作时间，则使用入参中的时间
        if (StringUtils.isBlank(currTime)) {
            currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        }
        // 来源渠道
        String sourceType = jsonOpInfo.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            // 默认web端门诊渠道
            sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        }
        paramMap.put("sourceType", sourceType);

        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
        paramMap.put("taskId", taskId);// 任务实例id
        paramMap.put("task", task);// 任务id
        paramMap.put("contentData", quesMap);
        paramMap.put("ptSchemeId", ptSchemeId);// 患者方案id
        paramMap.put("userId", userId);
        paramMap.put("updateTime", currTime);
        paramMap.put("updateAccept", updateAccept);
        paramMap.put("authorId", author);
        paramMap.put("tenantId", tenantId);
        paramMap.put("opCode", opCode);
        paramMap.put("queueId", queueId);
        paramMap.put("opNote", jsonOpInfo.getString("opNote"));
        paramMap.put("opType", jsonOpInfo.getString("opType"));
        paramMap.put("ptContentIds", ptContentIds);
        paramMap.put("updateAuname", updateAuname);
        paramMap.put("finishDate", finishDate);

        String taskNote = jsonTask.getString("taskNote");
        if (StringUtils.isBlank(taskNote)) {
            taskNote = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_CHECK_NOTE);
        }
        String nextDate = jsonTask.getString("nextDate");
        if (StringUtils.isBlank(nextDate)) {
            nextDate = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_NEXT_CHECK_DATE);
        }
        String nextAddress = jsonTask.getString("nextAddress");
        if (StringUtils.isBlank(nextAddress)) {
            nextAddress = (String) quesMap.get(Constants.QUESTION_ID_FOR_TR_TASK_NEXT_CHECK_ADDRESS);
        }
        paramMap.put("taskNote", taskNote);
        paramMap.put("nextDate", nextDate);
        paramMap.put("nextAddress", nextAddress);

        // 问卷类型，这里先写死0代表门诊问卷
        paramMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);

        Map<String, Object> retMap = new HashMap<String, Object>();
        if (schemeBusiTypes == Constants.SCHEME_BUSI_TYPE_0) {
            patientSerivce.modTaskContentData(paramMap);
        } else if (schemeBusiTypes == Constants.SCHEME_BUSI_TYPE_1) {
            retMap = ptTaskTreatService.submitTaskFunciton(paramMap);
        } else {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "暂不支持此方案业务类型！");
        }

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 查询查询门诊诊疗提交历史记录
    @ResponseBody
    @RequestMapping("/qryOprationHistoryList")
    public ResultModel<Map<String, Object>> qryOprationHistoryList(@RequestBody String arg) throws Exception {
        logger.warn("in qryOprationHistory----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        String taskId = jsonData.getString("taskId");
        String ptShemeId = jsonData.getString("ptSchemeId");
        if (StringUtils.isBlank(ptShemeId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，队列实例id为空！"));
        }

        String userId = jsonData.getString("userId");
        if (StringUtils.isBlank(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，用户id为空！"));
        }

        String schemeBusiType = jsonData.getString("schemeBusiType");
        if (StringUtils.isBlank(schemeBusiType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，任务id为空！"));
        }

        String queueId = jsonData.getString("queueId");
        if (StringUtils.isBlank(queueId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，队列id为空！"));
        }

        int schemeBusiTypes = Integer.parseInt(schemeBusiType);

        // 拼接入参
        Map<String, Object> mapIn = new HashMap<String, Object>();
        mapIn.put("userId", userId);
        mapIn.put("taskId", taskId);
        mapIn.put("ptShemeId", ptShemeId);
        mapIn.put("queueId", queueId);
        // mapIn.put("page", rows * (page - 1));
        // mapIn.put("rows", rows);
        mapIn.put("schemeBusiType", schemeBusiTypes);
        Map<String, Object> mapOut = ptTaskTreatService.getOprationHistoryList(mapIn);

        return new ResultModel<Map<String, Object>>(mapOut);
    }

    // 查询查询门诊诊疗某一记录的详细信息
    @ResponseBody
    @RequestMapping("/qryOprationHisResource")
    public ResultModel<Map<String, Object>> qryOprationHisResource(@RequestBody String arg) throws Exception {
        logger.warn("in qryOprationHisResource----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        String ptTask = jsonData.getString("ptTask");
        if (StringUtils.isBlank(ptTask)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，任务实例id为空！"));
        }

        String userId = jsonData.getString("userId");
        if (StringUtils.isBlank(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，用户id为空！"));
        }

        String schemeBusiType = jsonData.getString("schemeBusiType");
        if (StringUtils.isBlank(schemeBusiType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，任务id为空！"));
        }
        int schemeBusiTypes = Integer.parseInt(schemeBusiType);

        // 拼接入参
        Map<String, Object> mapIn = new HashMap<String, Object>();
        mapIn.put("userId", userId);
        mapIn.put("ptTask", ptTask);
        mapIn.put("schemeBusiType", schemeBusiTypes);
        retMap = ptTaskTreatService.getOprationHistory(mapIn);

        return new ResultModel<Map<String, Object>>(retMap);
    }

    // 患者信息List查询
    @ResponseBody
    @RequestMapping("/patientQueueListQuery")
    public ResultModel<HashMap<String, Object>> qryPatientQueueSchemeList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
        logger.warn("in qryPatientQueueSchemeList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            // 默认查询当日待随访的患者
            flag = "0";
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        String hisNo = jsonData.getString("hisNo");// 科研编号
        String fuzzyVar = jsonData.getString("fuzzyVar");// 姓名或科研编号
        if (!StringUtils.isEmpty(fuzzyVar)) {
            paramMap.put("fuzzyVar", fuzzyVar.replace(" ", "") + "%");
        }
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (!StringUtils.isEmpty(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (!StringUtils.isEmpty(userName)) {
            paramMap.put("userName", userName);
            //增加通过拼音查询用户
            paramMap.put("namePinyin", userName.toLowerCase()+"%");
            //名字简拼
            paramMap.put("nameInitial", userName.toLowerCase()+"%");
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("sourceType", jsonData.getString("opType"));
        paramMap.put("premature", jsonData.getString("premature"));
        paramMap.put("qryEndTime", jsonData.getString("qryEndTime"));
        paramMap.put("qryStartTime", jsonData.getString("qryStartTime"));
        if (!StringUtils.isEmpty(hisNo)) {
            paramMap.put("hisNo", hisNo);
        }

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        // 特殊处理一妇婴倍力多项目
        paramMap.put("showFlag", jsonData.getString("showFlag"));

        HashMap<String, Object> retMap = patientSerivce.qryPatientQueueSchemeList(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }

        return new ResultModel<HashMap<String, Object>>(retMap);
    }

    // 患者信息List查询
    @ResponseBody
    @RequestMapping("/patientListForDatatableQuery")
    public Map<String, Object> qryPatientListForDatatable(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in qryPatientQueueSchemeList----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        // String authorId = "18812345678";
        // String tenantId = "aaa";

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            // 默认查询当日待随访的患者
            flag = "0";
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("userName", userName);
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("sourceType", jsonData.getString("opType"));
        // paramMap.put("premature", jsonData.getString("premature"));

        Integer ageTo = jsonData.getInteger("ageTo");
        Integer ageFrom = jsonData.getInteger("ageFrom");

        Calendar to = Calendar.getInstance();
        if (ageTo != null) {
            to.add(Calendar.MONTH, -ageTo);
            paramMap.put("ageTo", DateUtil.getDate_8(to.getTime()));
        }

        Calendar from = Calendar.getInstance();
        if (ageFrom != null) {
            from.add(Calendar.MONTH, -ageFrom);
            // from.set(Calendar.DAY_OF_MONTH,
            // from.getActualMaximum(Calendar.DAY_OF_MONTH));
            paramMap.put("ageFrom", DateUtil.getDate_8(from.getTime()));
        }

        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }
        HashMap<String, Object> retMap = ptTaskTreatService.qryPatientQueueSchemeList(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }

        return retMap;
    }

    // 患者随访记录查询
    @ResponseBody
    @RequestMapping("/patientDealRecordListGeneral")
    public Map<String, Object> listPatientFollowDealRecord(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in listPatientFollowDealRecord----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String flag = jsonData.getString("flag");
        if (null == flag || "".equals(flag)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无flag节点！"));
        }
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (null != phoneNo && !"".equals(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (null != userName && !"".equals(userName)) {
            paramMap.put("userName", userName);
        }
        paramMap.put("flag", flag);
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("queueId", jsonData.getString("queueId"));
        paramMap.put("sourceType", jsonData.getString("opType"));
        paramMap.put("premature", jsonData.getString("premature"));
        paramMap.put("qryEndTime", jsonData.getString("qryEndTime"));
        paramMap.put("qryStartTime", jsonData.getString("qryStartTime"));
        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        HashMap<String, Object> retMap = ptTaskTreatService.qryPatientQueueSchemeList(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        retMap.put("success", true);

        return retMap;
    }
}
